package com.party.course.service.impl;

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import cn.hutool.core.date.DateUtil;
import com.party.business.domain.KcType;
import com.party.business.mapper.KcTypeMapper;
import com.party.common.utils.SecurityUtils;
import com.party.course.domain.CoachInfo;
import com.party.course.domain.StudentInfo;
import com.party.course.mapper.CoachInfoMapper;
import com.party.course.mapper.StudentInfoMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.party.course.mapper.PayGroupMapper;
import com.party.course.domain.PayGroup;
import com.party.course.service.IPayGroupService;

import cn.hutool.core.util.IdUtil;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * 交付小组Service业务层处理
 *
 * @author ruoyi
 * @date 2025-05-29
 */
@Service
public class PayGroupServiceImpl extends ServiceImpl<PayGroupMapper, PayGroup> implements IPayGroupService {
    @Autowired
    private PayGroupMapper payGroupMapper;
    @Resource
    private CoachInfoMapper coachInfoMapper;
    @Resource
    private KcTypeMapper kcTypeMapper;;
    @Resource
    private StudentInfoMapper studentInfoMapper;

    /**
     * 查询交付小组
     *
     * @param id 交付小组主键
     * @return 交付小组
     */
    @Override
    public PayGroup view(String id) {
        PayGroup payGroup = payGroupMapper.selectPayGroupById(id);
        if (StrUtil.isNotEmpty(payGroup.getMemberIds())) {
            String[] members = payGroup.getMemberIds().split(",");
            List<CoachInfo> coachInfos = coachInfoMapper.selectByIds(Arrays.asList(members));
            payGroup.setMembers(coachInfos);
            ;
            payGroup.setMemberIdList(Arrays.asList(members));
        }
        return payGroup;
    }

    /**
     * 查询交付小组列表
     *
     * @param payGroup 交付小组
     * @return 交付小组
     */
    @Override
    public List<PayGroup> findList(PayGroup payGroup) {
        if (StrUtil.isEmpty(payGroup.getCreateBy())){
            payGroup.setCreateBy(SecurityUtils.getDataPower());
        }
        return payGroupMapper.selectPayGroupList(payGroup);
    }

    /**
     * 新增交付小组
     *
     * @param payGroup 交付小组
     * @return 结果
     */
    @Override
    @Transactional
    public int add(PayGroup payGroup) {
        if (StrUtil.isEmpty(payGroup.getBotKey())) {
            throw new RuntimeException("企微群聊机器人设置不能为空!");
        }
//        else {
//            String url = payGroup.getBotKey();
//            String key = url.substring(url.indexOf("key=") + 4);
//            payGroup.setBotKey(key);
//        }
        payGroup.setId(IdUtil.simpleUUID());
        payGroup.setDelFlag("0");
        addLabelNames(payGroup);
        return payGroupMapper.insert(payGroup);
    }

    public void addLabelNames(PayGroup payGroup) {
        //课程分类
        if (StrUtil.isNotEmpty(payGroup.getClassTypeId())) {
            KcType kcType = kcTypeMapper.selectKcTypeById(payGroup.getClassTypeId());
            if (ObjectUtil.isNotEmpty(kcType)) payGroup.setClassTypeName(kcType.getName());
        }
        //交付组长
        if (StrUtil.isNotEmpty(payGroup.getUserGroupId())) {
            CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(payGroup.getUserGroupId());
            if (ObjectUtil.isNotEmpty(coachInfo)) {
                payGroup.setUserGroupName(coachInfo.getName());
                coachInfo.setPayGroupId(payGroup.getId());
                coachInfo.setPayGroupName(payGroup.getName());
                coachInfoMapper.updateById(coachInfo);
            }
        }
        //小组成员
        if (StrUtil.isNotBlank(payGroup.getMemberIds())) {
            //清空教练原来绑定的交付小组
            PayGroup group = payGroupMapper.selectPayGroupById(payGroup.getId());
            if (ObjectUtil.isNotEmpty(group) && StrUtil.isNotEmpty(group.getMemberIds())) {
                String[] ids = group.getMemberIds().split(",");
                if (ids.length > 0) {
                    coachInfoMapper.deleteGroup(Arrays.asList(ids));
                }
            }
            String[] members = payGroup.getMemberIds().split(",");
            String memberNames = "";
            for (String member : members) {
                CoachInfo coachInfo = coachInfoMapper.selectCoachInfoById(member);
                if (ObjectUtil.isNotEmpty(coachInfo)) {
                    memberNames += coachInfo.getName() + ",";
                    coachInfo.setPayGroupId(payGroup.getId());
                    coachInfo.setPayGroupName(payGroup.getName());
                    coachInfoMapper.updateById(coachInfo);
                }
            }
            payGroup.setMemberNames(memberNames);
        }
    }

    /**
     * 修改交付小组
     *
     * @param payGroup 交付小组
     * @return 结果
     */
    @Override
    @Transactional

    public int updateEntity(PayGroup payGroup) {
        payGroup.setUpdateTime(DateUtil.date());
        addLabelNames(payGroup);
        return payGroupMapper.updateById(payGroup);
    }

    /**
     * 批量删除交付小组
     *
     * @param ids 需要删除的交付小组主键
     * @return 结果
     */
    @Override
    public int deleteIds(List<String> ids) {
        for (String id : ids) {
            List<CoachInfo> coachInfos = coachInfoMapper.findByGroup(id);
            if(CollectionUtil.isNotEmpty(coachInfos)){
                // 根据userId  把自己排除掉
                coachInfos = coachInfos.stream().filter(coachInfo -> !coachInfo.getRoleId().equals("108")).collect(Collectors.toList());
            }
            List<StudentInfo> studentInfos = studentInfoMapper.findByGroup(id);
            if (coachInfos.size() > 0 || studentInfos.size() > 0) {
                throw new RuntimeException("该交付小组下有教练或学员，不能删除!");
            }
        }
        return payGroupMapper.deletePayGroupByIds(ids);
    }

    /**
     * 删除交付小组信息
     *
     * @param id 交付小组主键
     * @return 结果
     */
    @Override
    public int deleteById(String id) {
        return payGroupMapper.deletePayGroupById(id);
    }

    @Override
    public List<PayGroup> findAllByCreate(String createBy) {
        return payGroupMapper.findAllByCreate(createBy);
    }
}
